﻿using GetSmartIDEList.Lib.IOC;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GetSmartIDEList.Lib.AOP
{
    public class ContainerBuilder
    {
        private static IContainer _Container = new MyContainer();
        private static IServiceCollection _IServiceCollection = null;

        public ContainerBuilder(IServiceCollection services)
        {
            _IServiceCollection = services;
            this.ServiceCollectionToContainer(services);
        }
        /// <summary>
        /// 把注册到默认容器的关系 转到自己容器
        /// </summary>
        /// <param name="services"></param>
        private void ServiceCollectionToContainer(IServiceCollection services)
        {

            foreach (var service in services)
            {
                //按说是分类处理
                if (service.ImplementationFactory != null)
                {
                    //_Container.RegisterType(service.ServiceType, (provider => service.ImplementationFactory(provider)), this.TransLifetime(service.Lifetime));//尚未支持工厂注册
                }
                else if (service.ImplementationInstance != null)
                {
                    //_Container.RegisterType(service.ServiceType, service.ImplementationInstance);//尚未支持对象注册
                    _Container.RegisterType(service.ServiceType, service.GetType());
                }
                else
                {
                    _Container.RegisterType(service.ServiceType, service.ImplementationType, this.TransLifetime(service.Lifetime));
                }
            }
        }

        private LifetimeType TransLifetime(ServiceLifetime lifetime)
        {
            switch (lifetime)
            {
                case ServiceLifetime.Singleton:
                    return LifetimeType.Singleton;
                case ServiceLifetime.Scoped:
                    return LifetimeType.Scope;
                case ServiceLifetime.Transient:
                    return LifetimeType.Transient;
                default:
                    return LifetimeType.Transient;
            }
        }

        public void RegisterType<TFrom, TTo>(LifetimeType lifetimeType = LifetimeType.Transient) where TTo : TFrom
        {
            _Container.Register<TFrom, TTo>();
        }

        /// <summary>
        /// 提供容器实例
        /// </summary>
        /// <returns></returns>
        public IServiceProvider GetServiceProvider()
        {
            return new ServiceProvider(_Container);
            //return new ServiceProvider(_Container, _IServiceCollection);
        }
    }
}
